package cfg

import (
	"fmt"
	"github.com/google/wire"
	"gopkg.in/yaml.v3"
	"io/ioutil"
	"log"
)

type Data struct {
	MySql Mysql `mapstructure:"mysql" json:"mysql" yaml:"mysql"` // mysql
}

type Mysql struct {
	Host     string `mapstructure:"host" json:"host" yaml:"host"`             // 服务器地址
	Port     string `mapstructure:"port" json:"port" yaml:"port"`             // 端口
	Dbname   string `mapstructure:"db-name" json:"database" yaml:"database"`  // 数据库名
	Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库用户名
	Password string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码
}

func (m *Mysql) Dsn() string {
	return m.Username + ":" + m.Password + "@tcp(" + m.Host + ":" + m.Port + ")/" + m.Dbname
}

type Server struct {
	Http Http `mapstructure:"http" json:"http" yaml:"http"` // 服务器地址
}

type Http struct {
	Addr string `mapstructure:"addr" json:"addr" yaml:"addr"` // 服务器地址
}

type Config struct {
	Server Server `mapstructure:"server" json:"server" yaml:"server"` // 服务配置
	Data   Data   `mapstructure:"data" json:"data" yaml:"data"`       // 服务配置
}

func ReadConfig() *Config {
	path := "week04/configs/config.yaml"
	yamlFile, err := ioutil.ReadFile(path)
	if err != nil {
		panic(fmt.Errorf("Fatal error read config file: %s \n", err))
	}

	var conf Config
	err = yaml.Unmarshal(yamlFile, &conf)
	if err != nil {
		log.Fatalf("Fatal error unmarshal config file: %v", err)
	}
	return &conf
}

var Provider = wire.NewSet(ReadConfig)
